<html>
<body>
<title>CS 143: Project 1B</title>

<h1>CS 143: Project 1B</h1>

<h3>Troy Tabrilla<br>103786596</h3>

<p>Type an SQL query in the box below:<br></p>

<form action="query.php" method="POST">
<textarea name="query" cols="60" rows="8">
<?php echo htmlentities($_POST['query']); ?>
</textarea>
<input type="submit" value="Submit">
</form>

<?php
	$db_connection = mysql_connect("localhost", "cs143", "");
	if (!$db_connection)
	{
		$errmsg = mysql_error($db_connection);
		print "Could not connect to database: $errmsg <br>";
		exit(1);
	}
		
	$db_selected = mysql_select_db("CS143", $db_connection);
	if (!$db_selected)
	{
		$errmsg = mysql_error($db_selected);
		print "Could not select database: $errmsg <br>";
		exit(1);
	}
	
	$query = $_POST['query'];
	
	/*preg_match("#^SELECT +(.*) FROM#i", $query, $match1);
	preg_match("#FROM +(.*) WHERE#i", $query, $match2);
	preg_match("#WHERE +(.*);$#i", $query, $match3);
	
	$select = mysql_real_escape_string($match1[1], $db_connection);
	$from = mysql_real_escape_string($match2[1], $db_connection);
	$where = mysql_real_escape_string($match3[1], $db_connection);
	
	if (!$select || !$from || !$where)
	{
		print "Could not escape string. <br>";
		exit(1);
	}
	
	$query_to_issue = sprintf("SELECT %s FROM %s WHERE %s;", $select, $from, $where);
	$rs = mysql_query($query_to_issue, $db_connection);*/
	
	$rs = mysql_query($query, $db_connection);
	if (!$rs)
	{
		print "Could not query database: ".mysql_error()."<br>";
		exit(1);
	}
	
	$row = mysql_fetch_row($rs);
	$numcols = count($row);
	
	print "<table border=\"1\">\n<tr>\n";
	for ($i= 0; $i < $numcols; $i++)
	{
		$temp = mysql_field_name($rs, $i);
		print "<th><center>$temp</center></th>\n";
	}
	print "</tr>\n";
	
	do
	{
		print "<tr>\n";
		for ($i = 0; $i < $numcols; $i++)
		{
			if ($row[$i] == NULL)
				print "<td><center>N/A</center></td>\n";
			else
				print "<td><center>$row[$i]</center></td>\n";
		}
		print "</tr>\n";
	} while ($row = mysql_fetch_row($rs));
	
	print "</table>";
	
	/*$affected = mysql_affected_rows($db_connection);
	print "Number of affected rows: $affected <br>";*/
	
	mysql_close($db_connection);
?>

</body>
</html>